#include "AdbUtils.h"
#include <Windows.h>
# include <process.h>


std::string get_current_path()
{
	wchar_t program_path[MAX_PATH];
	GetModuleFileNameW(NULL, program_path, sizeof(program_path));

	TCHAR* r = wcsrchr(program_path, '\\');
	std::string out;
	if (r)
	{
		Unicode_to_UTF8(program_path, r - program_path + 1, out);
	}
	else
		Unicode_to_UTF8(program_path, wcslen(program_path), out);

	return out;
}

int GetPort(const char* serial, const char* type)
{
	unsigned int h = hash(serial);
	h = hash(type, h);
	return (PORT_MIN + h % (PORT_MAX - PORT_MIN));
}



Thread::Thread(void)
{
	m_handle = 0;
}


Thread::~Thread(void)
{
}

unsigned int __stdcall Thread::threadMainCallback(void *arg)
{
	Thread *self = (Thread *)arg;
	self->OnExcute();
	self->m_handle = NULL;
	_endthread();
	return 0;
}

bool Thread::Start()
{
	m_handle = (HANDLE)_beginthreadex(NULL, 0, threadMainCallback,
		(void *)this, 0, NULL);
	assert(m_handle != NULL);
	return m_handle != NULL;
}

bool Thread::Join()
{
	if (m_handle == 0) return true;
	DWORD res;
	BOOL bres;
	do
	{
		res = WaitForSingleObject(m_handle, INFINITE);
		assert(res != WAIT_FAILED);
		bres = CloseHandle(m_handle);
		//assert(bres != 0);
		m_handle = 0;
		return true;
	} while (0);
	return false;
}


void ParserKeyValue(const char* data, int len, std::string& key, std::string& value, char space)
{
	if (len < 0)
		len = strlen(data);
	const char* dataEnd = data + len;
	bool isKey = true;
	bool skipSpace = true;
	while (data<dataEnd)
	{
		if (*data == space)
		{
			isKey = false;
			skipSpace = true;
		}
		else if (isKey)
		{
			if (skipSpace)
			{
				switch (*data)
				{
				case ' ':
				case '\t':
					break;
				default:
					key.push_back(*data);
					skipSpace = false;
				}
			}
			else
			{
				skipSpace = false;
				key.push_back(*data);
			}
		}
		else
		{
			if (skipSpace)
			{
				switch (*data)
				{
				case ' ':
				case '\t':
					break;
				default:
					value.push_back(*data);
					skipSpace = false;
				}
			}
			else
			{
				skipSpace = false;
				value.push_back(*data);
			}
		}
		++data;
	}
}
